package Day012_多线程2.demo03_并发包;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zhangyan
 * @date 2020/4/30 14:03
 */
/*
    Hashtable:线程安全,执行效率低一些
              对整个哈希表加锁

    ConcurrentHashMap:线程安全,执行效率高一些
                      CAS + 局部锁定,只锁定桶
 */
public class demo04_Hashtable_ConcurrentHashMap {
    public static void main(String[] args) throws InterruptedException {

        //创建任务
        MyRunnable3 mr3 = new MyRunnable3();
        //创建线程
        for (int i = 0; i < 1000; i++) {
            Thread t = new Thread(mr3);
            t.start();
        }

        Thread.sleep(2000);
        System.out.println("最后集合键值对的个数:" + mr3.map.size());
    }
}
/*
    键值对个数应该是1000个,但实际结果可能会大于1000 (键唯一)
*/

class MyRunnable3 implements Runnable {
    //Hashtable<Integer, Integer> map = new Hashtable<>();

    ConcurrentHashMap<Integer,Integer> map = new ConcurrentHashMap<>();

    @Override
    public void run() {
        //开始时间
        long start = System.currentTimeMillis();
        for (int i = 0; i < 1000; i++) {
            map.put(i, 0);
        }
        long end = System.currentTimeMillis();
        System.out.println((end - start) + "毫秒");
    }
}